// 图片上传API处理
const fs = require('fs');
const path = require('path');

// 创建上传目录
const uploadDir = path.join(__dirname, '../uploads');
if (!fs.existsSync(uploadDir)) {
    fs.mkdirSync(uploadDir, { recursive: true });
}

// 处理图片上传
function handleImageUpload(req, res) {
    if (req.method !== 'POST') {
        res.writeHead(405, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ success: false, message: '只支持POST方法' }));
        return;
    }

    // 简化的文件上传处理
    let body = '';
    req.on('data', chunk => {
        body += chunk.toString();
    });

    req.on('end', () => {
        try {
            // 解析multipart/form-data（简化版本）
            const boundary = req.headers['content-type'].split('boundary=')[1];
            const parts = body.split('--' + boundary);
            
            for (let part of parts) {
                if (part.includes('filename=')) {
                    const filenameMatch = part.match(/filename="([^"]+)"/);
                    if (filenameMatch) {
                        const filename = filenameMatch[1];
                        const fileData = part.split('\r\n\r\n')[1].split('\r\n--')[0];
                        
                        // 生成唯一文件名
                        const timestamp = Date.now();
                        const safeFilename = timestamp + '-' + filename.replace(/[^\w\.-]/g, '_');
                        const filePath = path.join(uploadDir, safeFilename);
                        
                        // 保存文件
                        const buffer = Buffer.from(fileData, 'binary');
                        fs.writeFileSync(filePath, buffer);
                        
                        // 返回成功响应
                        res.writeHead(200, { 'Content-Type': 'application/json' });
                        res.end(JSON.stringify({
                            success: true,
                            imageUrl: `/uploads/${safeFilename}`,
                            message: '图片上传成功'
                        }));
                        return;
                    }
                }
            }
            
            res.writeHead(400, { 'Content-Type': 'application/json' });
            res.end(JSON.stringify({ success: false, message: '未找到图片文件' }));
        } catch (error) {
            console.error('上传处理错误:', error);
            res.writeHead(500, { 'Content-Type': 'application/json' });
            res.end(JSON.stringify({ success: false, message: '服务器处理错误' }));
        }
    });
}

// 获取图片列表
function handleGetImages(req, res) {
    if (req.method !== 'GET') {
        res.writeHead(405, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ success: false, message: '只支持GET方法' }));
        return;
    }

    try {
        const files = fs.readdirSync(uploadDir);
        const images = files
            .filter(file => /\.(jpg|jpeg|png|gif|webp)$/i.test(file))
            .map(file => ({
                name: file,
                url: `/uploads/${file}`,
                size: fs.statSync(path.join(uploadDir, file)).size
            }));
        
        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ success: true, images: images }));
    } catch (error) {
        console.error('获取图片列表错误:', error);
        res.writeHead(500, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ success: false, message: '获取图片列表失败' }));
    }
}

// 删除图片
function handleDeleteImage(req, res) {
    if (req.method !== 'POST') {
        res.writeHead(405, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ success: false, message: '只支持POST方法' }));
        return;
    }

    let body = '';
    req.on('data', chunk => {
        body += chunk.toString();
    });

    req.on('end', () => {
        try {
            const data = JSON.parse(body);
            const imageUrl = data.imageUrl;
            
            if (!imageUrl) {
                res.writeHead(400, { 'Content-Type': 'application/json' });
                res.end(JSON.stringify({ success: false, message: '缺少图片URL' }));
                return;
            }
            
            // 从URL中提取文件名
            const filename = path.basename(imageUrl);
            const filePath = path.join(uploadDir, filename);
            
            if (fs.existsSync(filePath)) {
                fs.unlinkSync(filePath);
                res.writeHead(200, { 'Content-Type': 'application/json' });
                res.end(JSON.stringify({ success: true, message: '图片删除成功' }));
            } else {
                res.writeHead(404, { 'Content-Type': 'application/json' });
                res.end(JSON.stringify({ success: false, message: '图片文件不存在' }));
            }
        } catch (error) {
            console.error('删除图片错误:', error);
            res.writeHead(500, { 'Content-Type': 'application/json' });
            res.end(JSON.stringify({ success: false, message: '删除图片失败' }));
        }
    });
}

module.exports = {
    handleImageUpload,
    handleGetImages,
    handleDeleteImage
};